package com.example.waterme.data

import android.content.Context
import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.workDataOf
import com.example.waterme.PLANT_NAME_KEY
import com.example.waterme.worker.WaterWorker
import dagger.hilt.android.qualifiers.ApplicationContext
import java.util.concurrent.TimeUnit
import javax.inject.Inject

class WorkerWaterRepository @Inject constructor(@ApplicationContext context: Context) : WaterRepository {
    private val workManager = WorkManager.getInstance(context)

    override fun applySchedule(interval: Int, plantName: String) {
        val inputData = workDataOf(PLANT_NAME_KEY to plantName)
        val waterRequest = OneTimeWorkRequestBuilder<WaterWorker>()
            .setInitialDelay(interval.toLong(), TimeUnit.SECONDS)
            .setInputData(inputData)
            .build()
        workManager.enqueueUniqueWork(
            plantName,
            ExistingWorkPolicy.REPLACE,
            waterRequest
        )
    }
}
